package com.promotores;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;

import com.promotores.R;
import com.promotores.jsonparsing.JSONReaderListener;
import com.promotores.util.Parametros;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;


public class ActivityMenuPromotores extends Activity implements OnClickListener, JSONReaderListener {
	ProgressDialog progDialog;
	//ProgressThread progThread;
	Button btnPreAprobar;
	Button btnAprobar;
	//para probar
	Button btnPrueba;
	String flag;
	int flag_sincronizar;
	String emailOfSender = "dpevents02@gmail.com";
	String message_no_sync;
	ProgressDialog progressDialog = null;
	int flagProgressDialog = 1;
	ImageButton offline;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pr_menu);
        
        //C2DMReceiver c2dm = new C2DMReceiver();
        
        Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
        registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
        registrationIntent.putExtra("sender", emailOfSender);
        startService(registrationIntent);
        
        btnPreAprobar = (Button)findViewById(R.id.btnPreAprobarMenu);
        btnPreAprobar.setOnClickListener(this);
        btnAprobar = (Button)findViewById(R.id.btnAprobarMenu);        
        btnAprobar.setOnClickListener(this);
        
        //para probar
        btnPrueba = (Button)findViewById(R.id.btnPrueba);
        btnPrueba.setOnClickListener(this);   
        
        offline = (ImageButton)findViewById(R.id.imgOfflineMode);
        offline.setOnClickListener(this);
        if (Parametros.isOffline_mode()){
        	offline.setVisibility(View.VISIBLE);
        }
    }
    
    
    public void sincronizar(){
    	
//    	if (!isNetworkAvailable()){
//    		Toast.makeText(this, "No hay conexión disponible", Toast.LENGTH_LONG).show();
//    		return;
//    	}
    	
    	sync_offline_data();
    	
    	String message_nosync="";
    	
    	GestorParametro dbParametro = new GestorParametro(this);
	     //SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
	     String last_update_aux;
	     
	     //Parametros.setLast_update("2012-05-30'T'00:00:00'Z'");
	     last_update_aux = dbParametro.getLastUpdate();
	     dbParametro.addLastUpdate();
	     String prueba = dbParametro.getLastUpdate();
	     
	     if (last_update_aux != null){
	    	Parametros.setLast_update(last_update_aux);	     	
	     }
	     else{
	    	//Log.d("last_up",Parametros.getLast_update());
	    	Parametros.setLast_update("1990-01-01T00:00:00Z");
	     }
	     
	     
         //TipoPromocion         
         JsonTipoPromocion jsonTipoPromocion = new JsonTipoPromocion();         
         List<BeanTipoPromocion> listaTipoPromocion = jsonTipoPromocion.read(this);
         
         if (listaTipoPromocion==null){
        	 //Toast.makeText(this, "No sync TipoPromocion", Toast.LENGTH_LONG).show();
        	 Log.d("Sync","No sync TipoPromocion");
        	 message_nosync+=" TipoPromocion ";
         }
         else {
	         GestorTipoPromocion dbTipoPromocion = new GestorTipoPromocion(this);
	         for (int i=0; i<listaTipoPromocion.size(); i++){        
	             int result = listaTipoPromocion.get(i).getCreated_at().compareTo(Parametros.getLast_update());
	             if (result<0)
	             {
	                 dbTipoPromocion.updateTipoPromocion(listaTipoPromocion.get(i));
	                 Log.d("up-tpromo",listaTipoPromocion.get(i).getId()+" - "+listaTipoPromocion.get(i).getTipoPromocion());
	             }
	             else if (result>0) {
	            	 if (listaTipoPromocion.get(i).getDeleted().compareTo("0")==0){
	            		 dbTipoPromocion.addTipoPromocion(listaTipoPromocion.get(i));
	            		 Log.d("add-tppromo",listaTipoPromocion.get(i).getId()+" - "+listaTipoPromocion.get(i).getTipoPromocion());
	            	 }
	             }            
	         }
         }
         
         
         //Promocion         
         JsonPromocion jsonPromocion = new JsonPromocion();
         List<BeanPromocion> listaPromocion = jsonPromocion.read(this);        
         if (listaPromocion==null) {
        	 //Toast.makeText(this, "No sync Promocion", Toast.LENGTH_LONG).show();
        	 Log.d("Sync","No sync Promocion");
        	 message_nosync+=" Promocion ";
         }
         else {
	         GestorPromocion dbPromocion = new GestorPromocion(this);
	         
	         for (int i=0; i<listaPromocion.size(); i++){        
	             int result = listaPromocion.get(i).getCreated_at().compareTo(Parametros.getLast_update());
	             if (result<0)
	             {
	                 dbPromocion.updatePromocion(listaPromocion.get(i));
	                 Log.d("up-promo",listaPromocion.get(i).getId()+" - "+listaPromocion.get(i).getTipoPromocion().getId());
	             }
	             else if (result>0) {
	            	 if (dbPromocion.getPromocionExiste(listaPromocion.get(i).getId())==0){
		                 dbPromocion.addPromocion(listaPromocion.get(i));
		                 Log.d("add-promo",listaPromocion.get(i).getId()+" - "+listaPromocion.get(i).getTipoPromocion().getId());
	            	 }
	             }            
	         }
         }
         
         
         //TipoEvento         
         JsonTipoEvento jsonTipoEvento = new JsonTipoEvento();         
         List<BeanTipoEvento> listaTipoEvento = jsonTipoEvento.read(this);         
         if (listaTipoEvento==null) {
        	 //Toast.makeText(this, "No sync TipoEvento", Toast.LENGTH_LONG).show();
         	 Log.d("Sync","No sync TipoEvento");
         	 message_nosync+=" TipoEvento ";
         }
         else {
	         GestorTipoEvento dbTipoEvento = new GestorTipoEvento(this);
//	         List<BeanTipoEvento> listaTipoEventos = Parametros.getLstUser_type_events();
	    	 
//	         if (listaTipoEventos != null){
//	         for (int i=0; i<listaTipoEvento.size(); i++)
//	    		 for (int j=0; j<listaTipoEventos.size(); j++)
//	    			 if (listaTipoEvento.get(i).getId() == listaTipoEventos.get(j).getId()){
//	    				 listaTipoEvento.remove(i);
//	    				 break;
//	    			 }
//	         }
//	         
	    	 for (int i=0; i<listaTipoEvento.size(); i++){        
	             int result = listaTipoEvento.get(i).getCreated_at().compareTo(Parametros.getLast_update());
	             if (result<0)
	             {	
	                 dbTipoEvento.updateTipoEvento(listaTipoEvento.get(i));
	                 Log.d("up-tpevento",listaTipoEvento.get(i).getId()+" - "+listaTipoEvento.get(i).getTipoEvento());
	             }
	             else if (result>0) {
	                 dbTipoEvento.addTipoEvento(listaTipoEvento.get(i));
	                 Log.d("add-tpevento",listaTipoEvento.get(i).getId()+" - "+listaTipoEvento.get(i).getTipoEvento());
	             }            
	         }
	         
	         //else
	        //	 Toast.makeText(this, "No TipoEvento", Toast.LENGTH_LONG).show();
	     }
        
         
         //Evento    
         
         JsonEvento jsonEvento = new JsonEvento();         
         List<BeanEvento> listaEvento = jsonEvento.read(this);        
                  
         if (listaEvento==null) {
        	 //Toast.makeText(this, "No sync Evento", Toast.LENGTH_LONG).show();
        	 Log.d("Sync","No sync Evento");
        	 message_nosync+= " Evento ";
         }
         else {
        	 GestorEvento dbEvento = new GestorEvento(this);
	         for (int i=0; i<listaEvento.size(); i++){
	
	             int result = listaEvento.get(i).getCreated_at().compareTo(Parametros.getLast_update());
	             if (result<0)
	             {
	                 dbEvento.updateEvento2(listaEvento.get(i));
	                 Log.d("up-evento",listaEvento.get(i).getId()+" - "+listaEvento.get(i).getTipoEvento());
	             }
	             else if (result>0) {
	                 dbEvento.addEvento(listaEvento.get(i),"1");
	                 Log.d("add-evento",listaEvento.get(i).getId()+" - "+listaEvento.get(i).getTipoEvento());
		             }     
	         }
         } 
         message_no_sync=message_nosync;
         clean_old_data();
         flagProgressDialog = 0;
    }

	private void clean_old_data() {
		// TODO Auto-generated method stub
		
		//Eventos
		GestorEvento dbEvento = new GestorEvento(this);
		dbEvento.cleanData();
		//Promociones
		GestorPromocion dbPromocion = new GestorPromocion(this);
		//dbPromocion.cleanData();
	}

	private void sync_offline_data() {
		// TODO Auto-generated method stub
		
		//Eventos
		GestorEvento dbEvento = new GestorEvento(this);
		dbEvento.syncData();
		//Promociones
		GestorPromocion dbPromocion = new GestorPromocion(this);
		dbPromocion.syncData();
		List<BeanEvento> listaEventos = dbEvento.getAllNotSaved();
		List<BeanPromocion> listaPromocion = dbPromocion.getAllPromocionNotSaved();
		if (listaEventos.isEmpty() && listaPromocion.isEmpty()){
			Parametros.setOffline_mode(false);
//			offline.setVisibility(View.INVISIBLE);
			offline.setVisibility(View.GONE);
			offline.invalidate();
		}
	}
	

	@Override
    public void onClick(View v){
    	
    	if (v.getId()==R.id.btnPreAprobarMenu){
    		Intent intent = new Intent();
    		intent.setClass(this, ActivityListarTipoEventos.class);
    		intent.putExtra("flag", "PRE");
    		startActivity(intent);
    	}
    	if (v.getId()==R.id.btnAprobarMenu){
    		Intent intent = new Intent();
    		intent.setClass(this, ActivityListarTipoEventos.class);
    		intent.putExtra("flag", "APR");
    		startActivity(intent);
    	}
    	//para probar
    	if (v.getId()==R.id.btnPrueba){
//            int typeBar = 0;
//            showDialog(typeBar);
//            
//            if (message_no_sync!="" && message_no_sync!=null){
//            	AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        		builder.setMessage("No Sync:"+message_no_sync).setPositiveButton("Aceptar", dialogClickListener).show();            	
//            }
    		if (!isNetworkAvailable()){
        		Toast.makeText(this, "No hay conexión disponible", Toast.LENGTH_LONG).show();
        		return;
        	}
			sincronizar();        				
    	}
    	if (v.getId()==R.id.imgOfflineMode){
    		if (Parametros.isOffline_mode())
    			Toast.makeText(this, "Data Offline presente", Toast.LENGTH_LONG).show();    		
    	}
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // do something on back.
        	Intent intent = new Intent();
        	intent.setClass(this, ActivityLogin.class);
        	startActivity(intent);
        	finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    	@Override
	    public void onClick(DialogInterface dialog, int which) {
	        switch (which){
	        case DialogInterface.BUTTON_POSITIVE:
	        	break;
	        }
    	}
    };

   
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}

	ProgressDialog myProgressDialog = null;
	int intContadorProgress=0;
	
	@Override
	public void onConnected() {
		// TODO Auto-generated method stub
		intContadorProgress++;
		if (intContadorProgress==1){
			myProgressDialog = ProgressDialog.show(this, "Cargando...", "Por favor esperar...", true);
			
		}
	}
	@Override
	public void onSent() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onFinished(JSONArray jArray) {
		// TODO Auto-generated method stub
		intContadorProgress--;
		if (intContadorProgress==0)
			myProgressDialog.dismiss();
	}

	@Override
	public void onResume(){
		super.onResume();
		if (Parametros.isOffline_mode()){
			ImageButton offline = (ImageButton)findViewById(R.id.imgOfflineMode);
			offline.setVisibility(View.VISIBLE);
			offline.invalidate();
        }
	}
}
